package de.tu_darmstadt.informatik.tk.lernsystem.dao;

import java.util.List;

import org.openrdf.result.Result;

import de.tu_darmstadt.informatik.tk.lernsystem.concepts.User;

/**
 * DAO for managing users.
 */
public class UserDao extends RdfDao {
	public static List<User> getAll() {
		try {
			Result<User> result = getConnection().getObjects(User.class);
			return transformResultToList(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static User getUserById(String userId) {
		try {
			Result<User> result = getConnection().getObjects(User.class);
			while (result.hasNext()) {
				User user = result.next();
				if (user.toString().equals(userId)) {
					return user;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static User getUserByUsername(String username) {
		try {
			Result<User> result = getConnection().getObjects(User.class);
			while (result.hasNext()) {
				User user = result.next();
				if (user.getUsername().toLowerCase().equals(username.toLowerCase())) {
					return user;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static User getUserByCredentialToken(String token) {
		if (token == null) {
			return null;
		}
		try {
			Result<User> result = getConnection().getObjects(User.class);
			while (result.hasNext()) {
				User user = result.next();
				if (user.getCredentialToken() != null && token.equals(user.getCredentialToken())) {
					return user;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static User createUser(String id) {
		return RdfDao.createObject(User.class, id);
	}
	
	public static User createUser() {
		return RdfDao.createObject(User.class, getRandomId());
	}
}
